"""
@name : 作业
@author : FanMY_71
@projectname: Pycharm练习
@Time: 2022/6/2-16:21
"""
import os
import pandas as pd


class User:
    user = {}
    serial_number = 0

    def __init__(self, name, passwd, money):
        self.name = name
        self.passwd = passwd
        self.money = money

    def buy_goods(self, good, weight):
        if weight > good.store:
            print("库存不足")
        else:
            pay = weight * good.price
            if self.money >= pay:
                self.money -= pay
                good.store -= weight
                print(f"购买成功，{self.name}剩余{self.money}元，"
                      f"{good.product_name}剩余库存{good.store}")
                u1 = {}

            else:
                print("余额不足")


class Register:
    def __init__(self, re_name, re_passwd, re_money, d1):
        self.re_name = re_name
        self.re_passwd = re_passwd
        self.re_money = re_money
        self.d1 = d1

    def cre_table(self, d1):
        u = pd.read_csv(dir_path)
        if self.re_name in set(u["name"]):
            print("该用户已存在")
            return
        else:
            my_user = pd.DataFrame(d1, index=[0])
            my_user.to_csv(dir_path, mode='a', header=False, index=False)


class Login:
    def __init__(self, lo_name, lo_passwd):
        self.lo_name = lo_name
        self.lo_passwd = lo_passwd

    def user_exist(self, lo_name, lo_passwd):
        fi = pd.read_csv('user_info.csv')

        verify = fi[(fi['name'] == lo_name) & (fi['passwd'] == float(lo_passwd))]
        # 验证该登入的用户是否存在
        if verify.empty:
            print('用户名或密码错误，或者您未注册')
            return verify
        else:
            print('登录成功！')
            return verify


class Goods:
    def __init__(self, classify, product_name, price, store):
        self.classify = classify
        self.product_name = product_name
        self.price = price
        self.store = store


apple = Goods("fruits", "apple", 8, 30)
pitaya = Goods("fruits", "pitaya", 4, 100)
goods = [apple, pitaya]


class menu:
    def adver(self):
        print("欢迎来到三乐购物系统".center(50, "*"))
        print("1.注册".center(40, " "))
        print("2.登录".center(40, " "))
        option = input("请输入你的选择: ")
        return option

    def shop_adver(self):
        print("欢迎来到三乐超市".center(40,"*"))
        print("{:<8}{:<8}{:<8}{:<8}".format("商品编号", "商品名称", "商品价格", "商品库存"))
        for good in goods:
            print("{:<11}{:<12}{:<14}{:<8}".format(goods.index(good), good.product_name, good.price, good.store))


def mkdir(dir_path):
    with open(dir_path, "w+") as fp:
        my_user = pd.DataFrame(columns=['name', 'passwd', 'money'])
        my_user.to_csv(dir_path, index=False)


if __name__ == "__main__":
    # 建立存放用户信息的文件
    dir_path = "./user_info.csv"
    # 判断文件是否存在
    if not os.path.exists(dir_path):
        mkdir(dir_path)
    menu = menu()
    while True:
        shopping_card = {}
        # 获得选项
        option = menu.adver()
        if option == "1":
            print("来到用户注册环节".center(40, "*"))
            newname = input("please input new name：")
            newpasswd = input("please input new passwd：")
            newmoney = input("please input new money：")
            d1 = {'name': newname, 'passwd': newpasswd, 'money': float(newmoney)}
            register = Register(newname, newmoney, newmoney, d1)
            register.cre_table(d1)
            print("注册成功")
        elif option == "2":
            print("欢迎您的登入".center(40, "*"))
            for i in range(3):
                if i <= 2:
                    lo_name = input("请输入你的名字：")
                    lo_passwd = input("请输入你的密码：")
                    login = Login(lo_name, lo_passwd)
                    ver = login.user_exist(lo_name, lo_passwd)
                    if not ver.empty:
                        ac_info = ver.set_index('name')
                        lo_money = ac_info['money'][lo_name]
                        user = User(lo_name, lo_passwd, lo_money)
                        menu.shop_adver()
                        while True:
                            goods_num = input("请输入要购买商品的编号")
                            if goods_num in list(range(len(goods))):
                                pass
                            elif goods_num.lower() == "q":
                                print("退出购物")
                                break
                            else:
                                print("你输入的商品编号有误，请重新输入")

                    else:
                        print(f"你还有{2 - i}次尝试的机会")
                else:
                    print("登入次数过多，请等一个小时之后再尝试")
